﻿#include<winsock2.h>
#include<errno.h>
#include<stdlib.h>
#include<iostream>
#include<string>

#pragma warning(disable : 4996)

#pragma comment(lib, "ws2_32.lib") //在链接阶段，需要将这个库⽂件链接到
//程序中，以确保运⾏时能够找到并调⽤Winsock2 API中实现的函数

std::string serverip = ""; //填写你的云服务器ip
uint16_t serverport = 8888; //填写你的云服务器开放的端口号
#define SIZE 1024

void TestClient()
{
	WSADATA wsaData; //保存初始化Winsock库时返回的信息
	int n = WSAStartup(MAKEWORD(2, 2), &wsaData); //初始化Winsock库
	if (n)
	{
		perror("WSAStarup failed");
		exit(1);
	}

	SOCKET clientSockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (clientSockfd == INVALID_SOCKET)
	{
		std::cerr << "socket creat failed !" << std::endl;
		WSACleanup();
		exit(1);
	}

	sockaddr_in serverAddr;
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(serverport);
	serverAddr.sin_addr.s_addr = inet_addr(serverip.c_str()); //字符串风格ip转网络序列

	int result = connect(clientSockfd, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
	if (result == SOCKET_ERROR)
	{
		std::cerr << "connect failed!" << std::endl;
		closesocket(clientSockfd);
		exit(2);
	}

	while (true)
	{
		std::string message;
		std::cout << "Please Enter@ ";
		std::getline(std::cin, message);
		if (message.empty())
			continue;
		send(clientSockfd, message.c_str(), message.size(), 0);

		char buffer[SIZE];
		int m = recv(clientSockfd, buffer, sizeof(buffer) - 1, 0);
		if (m > 0)
		{
			buffer[m] = '\0';
			std::cout << "Received from server:" << buffer << std::endl;
		}
		else
		{
			std::cerr << "recv failed !" << std::endl;
		}
		//对于指针和引用来说，权限不能放大只能缩小 T* -> const T*   T& -> const T&
		/*const char* p = "1111";
		char* q = p;*/

	}

	closesocket(clientSockfd);
	WSACleanup();
}


int main()
{
	TestClient();
	return 0;
}